package top.psjj.mall.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.psjj.mall.comment.Result;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    //处理系统业务异常
    @ExceptionHandler(MallException.class)
    public Result mallException(MallException mallException){
        log.error("业务异常："+mallException.getMsg());
        return new Result(mallException.getStatus(),mallException.getMsg());
    }
    //处理方法参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e){
        List<String> errorMessages = new ArrayList<String>();
        //获得全部的错误信息并封装到errorMessages集合中
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for(ObjectError objectError : allErrors){
            String message = objectError.getDefaultMessage();
            errorMessages.add(message);
        }
        log.error("方法参数校验异常："+errorMessages,toString());
        return new Result(MallExceptionEnum.METHOD_ARG_NOT_VALID.getStatus(), errorMessages.toString());
    }
    //处理方法参数校验异常2
    @ExceptionHandler(ConstraintViolationException.class)
    public Result constraintViolationException(ConstraintViolationException e){
        List<String> errorMessages = new ArrayList<String>();
        //获得全部的错误信息并封装到errorMessages集合中
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for(ConstraintViolation constraintViolation : constraintViolations){
            String message = constraintViolation.getMessage();
            errorMessages.add(message);
        }
        log.error("方法参数校验异常："+errorMessages,toString());
        return new Result(MallExceptionEnum.METHOD_ARG_NOT_VALID.getStatus(), errorMessages.toString());
    }
}
